package com.lemon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lemon.domain.*;
import com.lemon.domain.dto.OutboundOrderDetailsDto;
import com.lemon.domain.dto.OutboundOrderDto;
import com.lemon.domain.pageParam.OutboundOrderPageParam;
import com.lemon.domain.vo.SkuVo;
import com.lemon.domain.vo.WarehousingEntryUpVo;
import com.lemon.mapper.*;
import com.lemon.utils.UserThreadLocal;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.service.OutboundOrderService;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class OutboundOrderServiceImpl extends ServiceImpl<OutboundOrderMapper, OutboundOrder> implements OutboundOrderService{
    private final OutboundOrderMapper outboundOrderMapper;
    private final OutboundOrderDetailsMapper outboundOrderDetailsMapper;
    private final SkuMapper skuMapper;
    private final UserMapper userMapper;
    private final WarehousingEntryUpMapper warehousingEntryUpMapper;

    @Override
    public PageResult getPageByStatus(Integer page, Integer pageSize, Integer status,String invoiceCode) {
        PageHelper.startPage(page, pageSize);
        List<OutboundOrder> list = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(status) && status == 2){
            list = outboundOrderMapper.selectList(Wrappers.<OutboundOrder>lambdaQuery().ge(OutboundOrder::getStatus, status).like(ObjectUtil.isNotEmpty(invoiceCode),OutboundOrder::getInvoiceCode, invoiceCode));
        }else {
            list  = outboundOrderMapper.selectList(Wrappers.<OutboundOrder>lambdaQuery().eq(OutboundOrder::getStatus, status).like(ObjectUtil.isNotEmpty(invoiceCode),OutboundOrder::getInvoiceCode, invoiceCode));
        }
        Page<OutboundOrder> pageResult = (Page<OutboundOrder>) list;
        return new PageResult(pageResult.getTotal(),pageResult.getResult());
    }


    @Override
    @Transactional
    public void fahuo(OutboundOrderDetailsDto dto) {
        Integer outCount = dto.getOutCount();
        for (WarehousingEntryUpVo vo : dto.getWarehousingEntryUpVos()) {
            if (vo.getCount() == 0){
                break;
            }
            if (vo.getCount() <= outCount){
                outCount -= vo.getCount();
                WarehousingEntryUp entryUp = warehousingEntryUpMapper.selectById(vo.getId());
                entryUp.setCount(entryUp.getCount()-vo.getCount());
                warehousingEntryUpMapper.updateById(entryUp);
                if (entryUp.getCount() <=0){
                    warehousingEntryUpMapper.deleteById(entryUp);
                }
            }
            OutboundOrderDetails outboundOrderDetails = outboundOrderDetailsMapper.selectOne(Wrappers.<OutboundOrderDetails>lambdaQuery().eq(OutboundOrderDetails::getSkuId, dto.getSkuId()).eq(OutboundOrderDetails::getOutboundOrderId, dto.getId()));
            outboundOrderDetails.setOutCount(outCount);
            if (outCount == 0){
                outboundOrderDetails.setIsDel(2);
            }
            outboundOrderDetailsMapper.updateById(outboundOrderDetails);
        }
        OutboundOrder outboundOrder = outboundOrderMapper.selectById(dto.getId());
        outboundOrder.setStatus(2);
        outboundOrderMapper.updateById(outboundOrder);
    }

    @Override
    @Transactional
    public void add(OutboundOrderDto dto) {
        dto.setInvoiceCode(UUID.randomUUID().toString());
        dto.setStatus(1);
        dto.setCreateTime(LocalDateTime.now());
        Integer totalWeight = 0;
        Integer totalVolume = 0;
        Integer totalCount = 0;
        for (SkuVo skuVo : dto.getSkuVoList()) {
            Sku sku = skuMapper.selectById(skuVo.getId());
            totalWeight += sku.getProductWeight()*skuVo.getCount();
            totalVolume += sku.getProductVolume()*skuVo.getCount();
            totalCount += skuVo.getCount();
        }
        dto.setTotalCount(totalCount);
        dto.setTotalWeight(totalWeight);
        dto.setTotalVolume(totalVolume);
        User user = UserThreadLocal.get();
        dto.setEmpId(user.getId());
        OutboundOrder order = BeanUtil.toBean(dto, OutboundOrder.class);
        outboundOrderMapper.insert(order);
        dto.getSkuVoList().forEach(skuVo -> {
            OutboundOrderDetails outboundOrderDetails = new OutboundOrderDetails();
            outboundOrderDetails.setSkuId(skuVo.getId());
            outboundOrderDetails.setPreCount(skuVo.getCount());
            outboundOrderDetails.setOutCount(skuVo.getCount());
            outboundOrderDetails.setCode(skuVo.getCode());
            outboundOrderDetails.setOutboundOrderId(order.getId());
            outboundOrderDetails.setPickStatus(1);
            outboundOrderDetails.setCreateTime(LocalDateTime.now());
            outboundOrderDetails.setIsDel(1);
            outboundOrderDetailsMapper.insert(outboundOrderDetails);
        });
    }

    @Override
    public PageResult getPage(OutboundOrderPageParam param) {
        // 启动分页
        PageHelper.startPage(param.getPage(), param.getPageSize());

        // 构建查询条件
        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OutboundOrder> queryWrapper =
                Wrappers.<OutboundOrder>lambdaQuery();

        // 处理用户名称筛选
        if (ObjectUtils.isNotEmpty(param.getCustomerName())) {
            List<User> users = userMapper.selectList(Wrappers.<User>lambdaQuery()
                                                             .like(User::getUsername, param.getCustomerName()));

            if (CollUtil.isNotEmpty(users)) {
                List<Long> userIds = new ArrayList<>();
                for (User user : users) {
                    userIds.add(Long.valueOf(user.getId()));
                }
                queryWrapper.in(OutboundOrder::getEmpId, userIds);
            } else {
                // 如果没有匹配的用户，则返回空结果
                queryWrapper.eq(OutboundOrder::getId, -1); // 添加一个永远为false的条件
            }
        }

        // 添加其他查询条件
        queryWrapper
                .eq(ObjectUtil.isNotEmpty(param.getStatus()), OutboundOrder::getStatus, param.getStatus())
                .like(ObjectUtil.isNotEmpty(param.getInvoiceCode()), OutboundOrder::getInvoiceCode, param.getInvoiceCode())
                .orderByDesc(OutboundOrder::getCreateTime);


        // 执行查询，此时 PageHelper 会拦截这个查询并返回 Page 对象
        List<OutboundOrder> list = outboundOrderMapper.selectList(queryWrapper);

        // 转换为 Page 对象并返回结果
        Page<OutboundOrder> page = (Page<OutboundOrder>) list;
        return new PageResult(page.getTotal(), page.getResult());
    }



}
